using Microsoft.AspNetCore.Http;

namespace BackOffice.Application.Common;

public static class ClientInfoHelper
{
    /// <summary>
    /// 获取客户端真实IP地址
    /// </summary>
    /// <param name="httpContext">HTTP上下文</param>
    /// <returns>客户端IP地址</returns>
    public static string GetClientIpAddress(HttpContext httpContext)
    {
        try
        {
            // 尝试从各种头部获取真实IP
            var forwardedFor = httpContext.Request.Headers["X-Forwarded-For"].FirstOrDefault();
            if (!string.IsNullOrEmpty(forwardedFor))
            {
                // X-Forwarded-For可能包含多个IP，取第一个
                var firstIp = forwardedFor.Split(',')[0].Trim();
                if (!string.IsNullOrEmpty(firstIp) && firstIp != "unknown")
                {
                    return firstIp;
                }
            }

            var realIp = httpContext.Request.Headers["X-Real-IP"].FirstOrDefault();
            if (!string.IsNullOrEmpty(realIp))
            {
                return realIp;
            }

            var forwarded = httpContext.Request.Headers["X-Forwarded"].FirstOrDefault();
            if (!string.IsNullOrEmpty(forwarded))
            {
                return forwarded;
            }

            // 最后使用连接IP
            var remoteIp = httpContext.Connection.RemoteIpAddress?.ToString();
            if (!string.IsNullOrEmpty(remoteIp))
            {
                return remoteIp;
            }

            // 如果都获取不到，返回默认值
            return "127.0.0.1";
        }
        catch (Exception)
        {
            // 如果出现异常，返回默认值
            return "127.0.0.1";
        }
    }

    /// <summary>
    /// 获取客户端UserAgent
    /// </summary>
    /// <param name="httpContext">HTTP上下文</param>
    /// <returns>UserAgent字符串</returns>
    public static string GetUserAgent(HttpContext httpContext)
    {
        try
        {
            var userAgent = httpContext.Request.Headers["User-Agent"].FirstOrDefault();
            return !string.IsNullOrEmpty(userAgent) ? userAgent : "Unknown";
        }
        catch (Exception)
        {
            return "Unknown";
        }
    }
} 